package uebung07_h;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import tools.ColorConversions;
import tools.Image;
import tools.ShowImage;

public class Guttenberg {
	public static void main(String[] args) throws Exception {
		BufferedImage bim1 = ImageIO.read(Guttenberg.class.getClassLoader().getResourceAsStream("res/im2.png"));
		BufferedImage bim2 = ImageIO.read(Guttenberg.class.getClassLoader().getResourceAsStream("res/im6.png"));
		
		int[] im1 = ColorConversions.getFastLuminance(bim1.getRGB(0, 0, bim1.getWidth(), bim1.getHeight(), new int[bim1.getWidth()*bim1.getHeight()], 0, bim1.getWidth()), new int[bim1.getWidth()*bim1.getHeight()]);
		int[] im2 = ColorConversions.getFastLuminance(bim2.getRGB(0, 0, bim2.getWidth(), bim2.getHeight(), new int[bim2.getWidth()*bim2.getHeight()], 0, bim2.getWidth()), new int[bim2.getWidth()*bim2.getHeight()]);
		
		
		int win = 2, nrleft = bim1.getWidth(), nrright = bim2.getWidth(), ncleft = bim1.getHeight(), ncright = bim2.getHeight();

		int[] disparityMap = new int[nrleft*ncleft];
		
		int dispmin = 0, dispmax = 16; 
		
		for (int y = win, endy = nrleft-win; y<endy; y++) {
			for (int x = win, endx = ncright-win; x<endx; x++) {
				int prevSAD = Integer.MAX_VALUE;
				int temp = 0;
				int bestMatchSoFar = dispmin;
				for (int dispRange = -dispmin; dispRange<-dispmax; dispRange-=1) {
					int sad = 0;
					for (int a = -win; a<win; a++) {
						for (int b = -win; b<win; b++) {
							
							if (x-win+dispRange > 0) {
								temp = im1[x+b+(y+a)*nrleft]-im2[x+b+dispRange+(y+a)*nrright]; // indexess: (i+a,j+b) und (i+a,j+b+dispRange)
								if (temp<0)
									temp = temp*-1;
								sad = sad+temp;
							}
						}
					}
					if (prevSAD > sad) {
						prevSAD = sad;
						bestMatchSoFar = dispRange;
					}
				}
				disparityMap[x+y*ncleft] = -bestMatchSoFar;
			}
		}
		
		JFrame ff = new JFrame();
		ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final BufferedImage bi = new BufferedImage(nrleft, ncleft, BufferedImage.TYPE_INT_ARGB);
		
		int[] pixels = Image.buildRGB(disparityMap, disparityMap, disparityMap, new int[disparityMap.length]);
	
 		bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), disparityMap, 0, bi.getWidth());
		ff.add(new ShowImage(bi));
		
		ff.pack();
		ff.setVisible(true);
	}
}
